import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class Demo17 {
    public int port;
    public String serverIp;
    public DatagramSocket socket = null;
    public Demo17(String setverIp,int port) throws SocketException {
        socket = new DatagramSocket();
        this.serverIp = setverIp;
        this.port = port;
    }
    public void strat() throws IOException {
        System.out.println("客户端上线！");
        Scanner scanner = new Scanner(System.in);
        while(true){
            String request = scanner.next();
            //客户端需要发送给服务器 ，所以数据报的时候需要服务器IP 和 端口
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(this.serverIp),this.port);
            socket.send(requestPacket);
            DatagramPacket resposnePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(resposnePacket);
            //因为接受的是 byte数组 所以需要 转化成字符串
            String response = new String(resposnePacket.getData(), 0, resposnePacket.getLength());
            System.out.println(response);

        }
    }

    public static void main(String[] args) throws IOException {
        Demo17 demo17 = new Demo17("127.0.0.1", 9090);
        demo17.strat();
    }

}
